import { Button, message, Form, Avatar, Input } from 'antd';
import { useParams, useHistory } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import StreamPlayer from '../../components/streamPlayer';
import RTCClient from '../../../utils/agora-rtc-client';
import './index.scss';

function Detail() {
  const [channleName, setChannelName] = useState('');
  const [userName, setUserName] = useState('');
  const [avator, setAvator] = useState('')
  const [localStream, setLocalStream] = useState(null);
  const [remoteStreams, setRemoteStreams] = useState(null);
  const history = useHistory();
  const [showJoin, setShowJoin] = useState(false);
  const [showRefreshContent, setShowRefreshContent] = useState(false);

  const { channel, user } = useParams();

  const rtc = new RTCClient();

  const [appid, setAppid] = useState('ea84f56f4857492cb260d7f824916fd4');
  const [token, setToken] = useState('006ea84f56f4857492cb260d7f824916fd4IABOS8edIbdO+axtwXJ0GLkoRpp2eli6X2EFVHG9GYfO2gx+f9gAAAAAEAA1BQ7XP2fNXwEAAQA+Z81f');

  useEffect(() => {
    if (channel, user) {
      setChannelName(channel)
      setUserName(user);
      setAvator(user.toString().toUpperCase()[0]);
    }
  }, []);

  useEffect(() => {
    rtc.on('stream-added', (evt) => {
      let { stream } = evt
      console.log("[agora] [stream-added] stream-added", stream.getId())
      rtc.client.subscribe(stream);
    })

    rtc.on('stream-subscribed', (evt) => {
      let { stream } = evt
      console.log("[agora] [stream-subscribed] stream-added", stream.getId());
      const tempRemoteStreams = []
      console.log("cgfgfgfdfgdgfdfgdgfdfgdg", remoteStreams, stream);
      if (!remoteStreams.find((it) => it.getId() === stream.getId())) {
        debugger
        tempRemoteStreams.push(stream)
      };
      setRemoteStreams(tempRemoteStreams);
    })

    rtc.on('stream-removed', (evt) => {
      let { stream } = evt
      console.log('[agora] [stream-removed] stream-removed', stream.getId())
      let tempRemoteStreams = remoteStreams.filter((it) => it.getId() !== stream.getId());
      setRemoteStreams(tempRemoteStreams);
    })
  }, []);

  const joinChannnel = () => {
    rtc.joinChannel({
      appid,
      token,
      uid: null,
      channel: channleName
    }).then(() => {
      message.success('Join Success');
      rtc.publishStream().then((res) => {
        message.success('Publish Success');
        setLocalStream(res);
      }).catch((err) => {
        message.error('Publish Failure');
      })
    }).catch((err) => {
      message.error('Join Failure');
    })
    setShowJoin(true);
  }

  const leaveChannel = () => {
    setShowJoin(false);
    rtc.leaveChannel().then(() => {
      message.success('Leave Success');
    }).catch((err) => {
      message.error('Leave Failure')
    })
    setLocalStream(null);
    setRemoteStreams([]);
  }

  return (
    <div className='detail-container'>
      <div className='detail-container__user'>
        <section className='detail-container__user__user-section'>
          <Avatar size='large'>{avator}</Avatar>
          <div className='user'>{userName}</div>
        </section>
        <section className='detail-container__user__channel-section'>
          <div className='channel'>Channel Name: <span className='name'>{channleName}</span></div>
        </section>
        <section className='detail-container__user__error-msg-section'>
          <div className='text'>if join failure, refresh token and input new channel name</div>
          <div className='operator' onClick={() => setShowRefreshContent(!showRefreshContent)}>{showRefreshContent ? 'hide' : 'refresh'}</div>
        </section>
        {
          showRefreshContent && <section className='detail-container__user__oparation-container'>
            <div className='item'>
              <span className='text'>appId: </span>
              <Input value={appid} placeholder='new appId' onChange={(e) => setAppid(e.target.value)
              } />
            </div>
            <div className='item'>
              <span className='text'>token: </span>
              <Input value={token} placeholder='new token' onChange={(e) => setToken(e.target.value)} />
            </div>
            <div className='item'>
              <span className='text'>channel: </span>
              <Input value={channleName} placeholder='new channel name' onChange={(e) => setChannelName(e.target.value)} />
            </div>
          </section>
        }
        <section className='detail-container__user__operation-section'>
          <Button type='primary' disabled={showJoin} onClick={joinChannnel}>join</Button>
          <Button type='primary' disabled={!showJoin} onClick={leaveChannel}>leave</Button>
          <Button type='default' onClick={() => { history.push('/') }}>exit</Button>
        </section>
      </div>
      <div className='detail-container__agora'>
        <div className='detail-container__agora__container'>
          {
            localStream && <StreamPlayer stream={localStream} domId={localStream.getId()}></StreamPlayer>
          }
          {
            remoteStreams && remoteStreams.map((remoteStream) => (
              <StreamPlayer stream={remoteStream} domId={remoteStream.getId()}></StreamPlayer>
            ))
          }
        </div>
      </div>
    </div>
  )
}

export default Detail;